package com.dingceng.demo.photo

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.dingceng.demo.base.BaseViewModel
import com.dingceng.demo.base.isOK
import com.dingceng.demo.base.utils.NetUtil
import com.dingceng.demo.base.utils.log
import com.dingceng.demo.base.utils.toastCenter
import com.dingceng.demo.photo.net.PhotoService
import com.dingceng.demo.photo.net.SplashTraitData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class PhotoListModel : BaseViewModel() {
    val photoList =  MutableLiveData<List<SplashTraitData>>()

    fun getData(){
        showLoading.value = true
        /**
         * viewmodel里开启协程: viewModelScope.launch 不指定Dispatchers则默认在主线程
         */
        viewModelScope.launch(handler) {
            val result = NetUtil.getRetrofit().create(PhotoService::class.java)
                .getDemoTrait(NetUtil.getSignParams()).await() /**Retrofit这段代码会自动切到IO线程不用开发者操心*/
            /**以下代码会自动切换回主线程运行*/
            if (result.code== isOK){
                if (!result.data.isNullOrEmpty()){
                    photoList.postValue(result.data)/**postValue和.value区别在于：postvalue可以在IO线程使用，但赋值会延时回调到oberver*/
                    log("postValue测试",photoList.value.toString())/**所以这里打印value是null的，总结：使用postValue赋值不会马上生效*/
                }else{
                    toastCenter("没有找到相关内容")
                }
            }else{
                toastCenter(result.msg)
            }
            showLoading.value = false
        }
    }
}